﻿using System;
using System.Collections.Generic;
using System.Text;
using Pixysoft.Framework.Noebe.Consistency;
using System.Data;
using Pixysoft.Framework.Noebe.Orm.Controller;
using Pixysoft.Framework.Verifications;

namespace Pixysoft.Framework.Noebe.Orm.Core
{
    class CstOrmSession : OrmSession, ICstOrmSession
    {
        string groupCode = null;

        ICstNoebeCommand command = null;

        public CstOrmSession(ICstNoebeCommand command, string groupCode)
            : base(command)
        {
            this.command = command;

            this.groupCode = groupCode;
        }

        public override void SetCommand(INoebeCommand command)
        {
            throw Exceptions.UnexpectedResultException("cst orm noebe not support noebecommand. use setCommand(ICstNoebeCommand command) instead.");
        }

        public virtual void SetCstCommand(ICstNoebeCommand command)
        {
            this.command = command;
            base.SetCommand(command);
        }

        public override int Save(params object[] targets)
        {
            return SaveTo(groupCode, targets);
        }

        public int SaveTo(string groupCode, params object[] targets)
        {
            int affectCounter = 0;

            foreach (object target in targets)
            {
                if (target == null)
                    continue;

                ObjectProxy proxy = ConversionController.ObjectToProxy(target);

                //先 插入->修改 自己

                affectCounter += TrySaveObject(proxy, groupCode);

                proxy.GetObjectStruct().Status = StructStatus.Select;

                //然后 删除->插入->修改 建立关系表

                affectCounter += TrySaveValueRelation(proxy, groupCode);

                affectCounter += TrySaveLinkRelation(proxy, groupCode);

            }

            return affectCounter;
        }
    }
}
